

// 新增函数：根据数据更新设置面板
function updatePanelFromData(options) {
    if (!options) return;

    zIndexInput.value = options.zIndex;
    fontSizeRatioInput.value = options.fontSizeRatio.toFixed(3);
    paddingYRatioInput.value = options.paddingYRatio.toFixed(3);
    paddingXRatioInput.value = options.paddingXRatio.toFixed(3);
    borderRadiusInput.value = options.borderRadius;

    // RGB颜色值转换为十六进制
    const fontColorHex = rgbToHex(options.fontColor);
    const bgColorHex = rgbToHex(options.bgColor);
    const fontAlpha = getAlphaFromRgba(options.fontColor);
    const bgAlpha = getAlphaFromRgba(options.bgColor);

    fontColorInput.value = fontColorHex;
    fontAlphaInput.value = fontAlpha;
    bgColorInput.value = bgColorHex;
    bgAlphaInput.value = bgAlpha;
}

// 辅助函数：将rgb或rgba颜色值转换为十六进制
function rgbToHex(rgb) {
    if (rgb.startsWith('#')) return rgb;
    const parts = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+\.?\d*))?\)$/);
    if (!parts) return '#000000';

    const r = parseInt(parts[1], 10);
    const g = parseInt(parts[2], 10);
    const b = parseInt(parts[3], 10);

    return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase();
}

// 辅助函数：从rgba颜色值中提取透明度
function getAlphaFromRgba(rgba) {
    if (rgba === 'transparent') return 0;
    const parts = rgba.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+),\s*(\d+\.?\d*)\)$/);
    if (!parts) return 1;
    return parseFloat(parts[4]);
}











//保存图片
$saveBtn.on('click', function () {
    const image = $myImage[0];
    const imageContainer = $imageContainer[0];

    image.crossOrigin = 'anonymous';

    const loadImage = new Promise((resolve, reject) => {
        if (image.complete && image.naturalHeight !== 0) {
            resolve(image);
        } else {
            image.onload = () => resolve(image);
            image.onerror = () => reject('图片加载失败，无法保存。');
        }
    });

    loadImage.then(loadedImage => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');

        canvas.width = originalImageWidth;
        canvas.height = originalImageHeight;

        ctx.drawImage(loadedImage, 0, 0, originalImageWidth, originalImageHeight);

        const scaleFactorX = originalImageWidth / imageContainer.clientWidth;
        const scaleFactorY = originalImageHeight / imageContainer.clientHeight;
        $('.text-item').each(function () {
            const $this = $(this);
            const textContent = this.innerText;

            const liveTopPx = parseFloat($this.css('top'));
            const liveLeftPx = parseFloat($this.css('left'));
            const liveFontSizePx = parseFloat($this.css('font-size'));
            const liveColor = $this.css('color');
            const liveBgColor = $this.css('background-color');
            const livePaddingPx = $this.css('padding').split(' ').map(parseFloat);


            const scaledTop = liveTopPx * scaleFactorY;
            const scaledLeft = liveLeftPx * scaleFactorX;
            const scaledFontSize = liveFontSizePx * scaleFactorX;
            const scaledPaddingY = livePaddingPx[0] * scaleFactorY;
            const scaledPaddingX = livePaddingPx.length > 1 ? livePaddingPx[1] * scaleFactorX : scaledPaddingY;

            ctx.font = `bold ${scaledFontSize}px Arial, sans-serif`;
            const lines = textContent.split('\n');

            if (liveBgColor !== 'transparent' && rgbaToAlpha(liveBgColor) > 0) {
                ctx.fillStyle = liveBgColor;
                let totalTextWidth = 0;
                let lineHeights = 0;
                lines.forEach(line => {
                    const metrics = ctx.measureText(line);
                    totalTextWidth = Math.max(totalTextWidth, metrics.width);
                    lineHeights += scaledFontSize * 1.2;
                });
                ctx.fillRect(scaledLeft, scaledTop, totalTextWidth + scaledPaddingX * 2, lineHeights + scaledPaddingY * 2);
            }

            ctx.fillStyle = liveColor;
            ctx.shadowColor = 'rgba(0, 0, 0, 0.7)';
            ctx.shadowBlur = 4;
            ctx.shadowOffsetX = 2;
            ctx.shadowOffsetY = 2;
            ctx.textAlign = 'left';
            ctx.textBaseline = 'top';

            let lineY = scaledTop + scaledPaddingY;
            const lineHeight = scaledFontSize * 1.2;
            lines.forEach(line => {
                ctx.fillText(line, scaledLeft + scaledPaddingX, lineY);
                lineY += lineHeight;
            });
        });

        try {
            const dataURL = canvas.toDataURL('image/png');
            const link = document.createElement('a');
            link.download = 'edited_image.png';
            link.href = dataURL;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            showAlert('图片已成功保存!');
        } catch (e) {
            console.error('保存失败：', e);
            showAlert('保存失败！如果您通过本地文件打开，请使用本地服务器运行。');
        }
    }).catch(error => {
        console.error(error);
        showAlert(error);
    });
});